package com.wgchao.authmanager.application.filter;

import com.sun.tools.javac.util.List;
import com.wgchao.authmanager.infrastructure.exception.TokenDefectException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @ClassName: AuthenticationAspect
 * @author: wgchao
 * @createTime: 2020/5/12 4:57 PM
 * @Description: TODO
 */
@Aspect
@Component
@Order(-10)
public class AuthenticationAspect {

    @Autowired
    private TokenAuthentication tokenAuthentication;

    private AuthoAuthentication authoAuthentication;

    ThreadLocal<Long> beginTime = new ThreadLocal<Long>();

    @Pointcut("@annotation(authentication)")
    public void AuthenticationService(Authentication authentication) {
    }

    @Around("AuthenticationService(authentication)")
    public Object doAround(ProceedingJoinPoint joinPoint, Authentication authentication) throws Throwable{
        beginTime.set(System.currentTimeMillis());
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        //获取token
        String accessToken = request.getHeader("accessToken");
        if(StringUtils.isEmpty(accessToken)){
            throw new TokenDefectException("缺少身份令牌");
        }

        //token合法性验证
        String uname = tokenAuthentication.authentication(accessToken, authentication.type());

        //判断接口类型 是否需要接口权限检校
//        if(authentication.type().compareTo(AuthMethod.NORMAL) == 0){
//            authoAuthentication.authentication(uname);
//        }

        HttpSession session = request.getSession();
        session.setAttribute("uname", uname);

        return joinPoint.proceed();
    }
}
